package com.alliky.core.base;

import com.trello.rxlifecycle2.LifecycleProvider;

import java.lang.ref.WeakReference;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * @Description: DOTO
 * @Author: wxianing
 * @CreateDate: 2019/9/29 17:18
 */
public abstract class BasePresenter<M extends BaseModel, V extends IView>  implements Consumer<Disposable> {

    public V mRootView;
    public M mModel;

    //弱引用持有
    private WeakReference<LifecycleProvider> lifecycle;
    //管理RxJava，主要针对RxJava异步操作造成的内存泄漏
    private CompositeDisposable mCompositeDisposable;

    public BasePresenter(V view) {
        this.mRootView = view;
        mModel = createModel();
        mCompositeDisposable = new CompositeDisposable();
    }

    public void addSubscribe(Disposable disposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(disposable);
    }

    /**
     * 注入RxLifecycle生命周期
     *
     * @param lifecycle
     */
    public void injectLifecycleProvider(LifecycleProvider lifecycle) {
        this.lifecycle = new WeakReference<>(lifecycle);
    }

    public LifecycleProvider getLifecycleProvider() {
        return lifecycle.get();
    }

    protected abstract M createModel();

    /**
     * 解除绑定view，一般在onDestroy中调用
     */
    public void detachView() {

        if (mRootView != null) {
            this.mRootView = null;
        }

        if (mModel != null) {
            mModel.dispose();
            mModel = null;
        }

        //Presenter销毁时会执行，同时取消所有异步任务
        if (mCompositeDisposable!=null){
            mCompositeDisposable.clear();
        }

    }

    @Override
    public void accept(Disposable disposable) throws Exception {
        addSubscribe(disposable);
    }

    /**
     * View是否绑定
     *
     * @return
     */
    public boolean isViewAttached() {
        return mRootView != null;
    }

}